package me.zhengjie.modules.quartz.domain

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.bean.copier.CopyOptions
import com.fasterxml.jackson.annotation.JsonTypeName
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.persistence.*
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import me.zhengjie.common.base.BaseEntity
import me.zhengjie.common.utils.JacksonUtil
import me.zhengjie.modules.system.domain.Area
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.redis.core.RedisHash
import java.sql.Timestamp
import kotlin.jvm.Transient

/**
 * @author Kuki Wu
 * @date 2019-01-07
 */
@Entity
@Table(name = "sys_quartz_job")
@JsonTypeName("QuartzJob")
@RedisHash("quartzjob")
data class QuartzJob (
    @Id
    @Column(name = "job_id")
    @Schema(description = "id", hidden = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: @NotNull(groups = [Update::class]) Long? = null,

    @Transient
    @Schema(description = "用于子任务唯一标识", hidden = true)
    var uuid: String? = null,

    // 定时器名称
    @Schema(description = "定时器名称")
    @Column(name = "job_name")
    var jobName: String? = null,

    // Bean名称
    @Schema(description = "Bean名称")
    @Column(name = "bean_name")
    var beanName: @NotBlank String? = null,

    // 方法名称
    @Schema(description = "方法名称")
    @Column(name = "method_name")
    var methodName: @NotBlank String? = null,

    // 参数
    @Schema(description = "参数")
    @Column(name = "params")
    var params: String? = null,

    // cron表达式
    @Schema(description = "cron表达式")
    @Column(name = "cron_expression")
    var cronExpression: @NotBlank String? = null,

    // 状态
    @Schema(description = "状态，暂停或启动")
    @Column(name = "is_pause")
    var isPause: Boolean = false,

    @Schema(description =  "负责人")
    private var personInCharge: String? = null,

    @Schema(description =  "报警邮箱")
    var email: String? = null,

    @Schema(description =  "子任务")
    var subTask: String? = null,

    @Schema(description = "失败后暂停")
    var pauseAfterFailure: Boolean? = null,

    // 备注
    @Schema(description = "备注")
    var description: @NotBlank String? = null,

): BaseEntity() {

    fun copy(source: QuartzJob?) {
        BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true))
    }

    annotation class Update
    companion object {
        const val JOB_KEY = "JOB_KEY"

        fun fromJson(json: String): Area? {
            val obj=JacksonUtil.parseObject(json, Area::class.java)!!
            return when(obj){
                is Area -> obj
                else -> null
            }
        }
    }
}